<template>
  <div
    v-loading="saveLoading || getDetailLoading || getWarehouseEntryDetailGoodListLoading"
    element-loading-text="加载中..."
    class="warehouse-entry-wrapper"
  >
    <div class="main">
      <header class="header">
        <div class="title">
          <div v-if="form.id" class="detail">
            <i class="iconfont icon-detail"></i>
            <span class="text">入库详情</span>
          </div>
          <div v-else class="new">新增入库</div>
        </div>
        <div class="btn_group">
          <HPlainButton @click="onSave">保存</HPlainButton>
          <HPlainButton type="warning" @click="onCheck">{{
            form.id ? '审核' : '保存并审核'
          }}</HPlainButton>
          <HButton @click="onCancel">取消</HButton>
          <HPlainButton v-if="form.id" type="error" @click="rejectDialogVisible = true"
            >驳回</HPlainButton
          >
        </div>
      </header>

      <div class="divider_line"></div>

      <div class="form_container">
        <div v-if="route.params.id" class="title">
          <h4 class="into_storage_no">入库单号: {{ warehouseEntryNo }}</h4>
          <HStatus type="warning">待审核</HStatus>
        </div>
        <el-form
          ref="formInstance"
          :model="form"
          :rules="formRules"
          class="form"
          label-position="top"
          inline-message
        >
          <div class="form_item_container">
            <!-- 单据类型 -->
            <el-form-item label="单据类型" prop="typeId">
              <el-select
                v-model="form.typeId"
                :loading="getDocumentTypeOptionsLoading"
                placeholder="单据类型"
                filterable
                clearable
                :filter-method="handleGetDocumentTypeOptions"
              >
                <el-option
                  v-for="(item, index) in documentTypeOptions"
                  :key="index"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>

            <!-- 单据日期 -->
            <el-form-item label="单据日期">
              <el-date-picker
                v-model="form.createTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm"
                @change="handleChangeCreateTime"
              />
            </el-form-item>
          </div>
          <div class="form_item_container">
            <!-- 仓库类型 -->
            <el-form-item label="仓库类型" prop="storeType">
              <el-select
                v-model="form.storeType"
                placeholder="仓库类型"
                disabled
                @change="onDocumentTypeChange"
              >
                <el-option
                  v-for="(item, index) in storeType"
                  :key="index"
                  :value="item.value"
                  :label="item.title"
                />
              </el-select>
            </el-form-item>

            <!-- 预计入库时间 -->
            <el-form-item label="预计入库时间">
              <el-date-picker
                v-model="form.estimateTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm"
                @change="handleChangeEstimateWarehouseEntryTime"
              />
            </el-form-item>
          </div>
          <div class="form_item_container">
            <!-- 单据来源 -->
            <el-form-item label="单据来源">
              <el-select v-model="form.source" placeholder="单据来源" clearable>
                <el-option
                  v-for="(item, index) in source"
                  :key="index"
                  :value="item.value"
                  :label="item.title"
                />
              </el-select>
            </el-form-item>

            <!-- 入库备注 -->
            <el-form-item label="入库备注">
              <el-input
                v-model.trim="form.remark"
                clearable
                placeholder="入库备注"
                type="textarea"
                resize="both"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="table_container">
        <div class="title">产品列表</div>
        <div class="table">
          <el-table
            ref="tableInstance"
            :border="true"
            :data="goodList"
            show-summary
            :summary-method="getSummary"
            height="100%"
            resizable
            stripe
            :row-class-name="getRowClassName"
          >
            <!-- 序号 -->
            <el-table-column
              show-overflow-tooltip
              label="序号"
              width="60"
              fixed="left"
              :align="'center'"
            >
              <template #default="{ row, $index }">{{ row.isFixed ? '' : $index }}</template>
            </el-table-column>

            <!-- 类型 -->
            <el-table-column show-overflow-tooltip label="类型" width="82">
              <template #default="{ row }">
                {{ row.isFixed ? '' : row.type == 1 ? '成品' : '物料' }}
              </template>
            </el-table-column>

            <!-- 产品名称 -->
            <el-table-column
              prop="goodsName"
              show-overflow-tooltip
              label="产品名称"
              min-width="100"
            />

            <!-- 型号 -->
            <!-- <el-table-column prop="goodsModel" show-overflow-tooltip label="型号" min-width="100" /> -->

            <!-- 规格 -->
            <el-table-column
              prop="goodsSpecName"
              show-overflow-tooltip
              label="规格"
              min-width="100"
            />

            <!-- 品牌 -->
            <!-- <el-table-column prop="goodsBrand" show-overflow-tooltip label="品牌" min-width="100" /> -->

            <!-- 分类 -->
            <el-table-column prop="goodsType" show-overflow-tooltip label="分类" min-width="120" />

            <!-- 单位 -->
            <el-table-column prop="unit" show-overflow-tooltip label="单位" width="90" />

            <!-- 仓库 -->
            <el-table-column label="仓库" width="150">
              <template #header>
                <div class="table-header">
                  仓库
                  <el-popover ref="popover" placement="top" trigger="click" :width="240">
                    <h5 style="margin-bottom: 10px">批量填充仓库</h5>
                    <div class="popover-container">
                      <el-select
                        v-model="allStoreId"
                        placeholder="请选择"
                        style="width: 100%"
                        :filter-method="handleGetWarehouseOptions"
                        filterable
                      >
                        <el-option
                          v-for="(item, index) in warehouseOptions"
                          :key="index"
                          :value="item.id"
                          :label="item.name"
                        />
                      </el-select>
                      <h-button type="primary" @click="onChangeAllStore">确定</h-button>
                    </div>
                    <template #reference>
                      <h-plain-button :height="16" :padding-lr="4">批量</h-plain-button>
                    </template>
                  </el-popover>
                </div>
              </template>
              <template #default="{ row, $index }">
                <el-select
                  v-if="!row.isFixed"
                  v-model="row.storeId"
                  placeholder="请选择"
                  :filter-method="handleGetWarehouseOptions"
                  filterable
                  :class="{ selectError: isVerifyGoods && !row.storeId }"
                  @change="handleSelectWarehouse(row, $index)"
                >
                  <el-option
                    v-for="(item, index) in warehouseOptions"
                    :key="index"
                    :value="item.id"
                    :label="item.name"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 仓位 -->
            <el-table-column label="仓位" width="150">
              <template #header>
                <div class="table-header">
                  仓位
                  <el-popover ref="popover2" placement="top" trigger="click" :width="240">
                    <h5 style="margin-bottom: 10px">批量填充仓位</h5>

                    <div class="popover-container">
                      <el-select
                        v-if="goodList[1]"
                        v-model="allWarehousePositionId"
                        placeholder="请选择"
                        :teleported="false"
                        filterable
                        style="width: 100%"
                        :disabled="!isAllWarehouseEnablePosition"
                        :filter-method="handleChangeAllWarehousePositionOptions"
                        :loading="getAllGoodWarehousePositionOptionsLoading"
                      >
                        <el-option
                          v-for="(item, index) in goodList[1].warehousePositionOptions"
                          :key="index"
                          :value="item.id"
                          :label="item.name"
                        />
                      </el-select>
                      <h-button type="primary" @click="onChangeAllGoodWarehousePosition"
                        >确定</h-button
                      >
                    </div>
                    <template #reference>
                      <h-plain-button :height="16" :padding-lr="4">批量</h-plain-button>
                    </template>
                  </el-popover>
                </div>
              </template>
              <template #default="{ row, $index }">
                <el-select
                  v-if="!row.isFixed"
                  v-model="row.storePositionId"
                  placeholder="请选择"
                  filterable
                  clearable
                  :disabled="!getWarehouseEnableStatus(row.storeId)"
                  :filter-method="
                    (val: string) => handleGetWarehousePositionOptions(val, row.storeId, $index)
                  "
                  :class="{
                    selectError:
                      isVerifyGoods &&
                      !getWarehouseEnableStatus(row.storeId) &&
                      !row.storePositionId,
                  }"
                  @change="getGoodStock(row, $index)"
                >
                  <el-option
                    v-for="(item, index) in row.warehousePositionOptions"
                    :key="index"
                    :value="item.id"
                    :label="item.name"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 可用库存 -->
            <el-table-column prop="systemStock" show-overflow-tooltip label="可用库存" width="95">
              <template #header>
                <span>可用库存</span>
                <el-tooltip content="可用库存 = 即时库存 - 占用库存" placement="top">
                  <el-icon>
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
              </template>
            </el-table-column>

            <!-- 选择条码 -->
            <el-table-column
              prop="stockCodeVos"
              show-overflow-tooltip
              label="条码"
              min-width="150"
            >
              <template #default="{ row }">
                <template v-if="!row.isFixed">
                  <h-link v-if="row.stockCodeVos.length > 0" @click="onSelectSnCode(row)">{{
                    row.stockCodeVos[0].code
                  }}</h-link>
                  <h-link v-else @click="onSelectSnCode(row)">选择条码</h-link>
                </template>
              </template>
            </el-table-column>

            <!-- 数量 -->
            <el-table-column prop="qty" label="数量" min-width="100">
              <template #header>
                <div class="table-header">
                  数量
                  <el-popover placement="top" trigger="click" :width="160">
                    <h5 style="margin-bottom: 10px">批量填充数量</h5>
                    <div class="popover-container">
                      <el-input
                        v-model.trim="allQty"
                        placeholder="请输入"
                        maxlength="5"
                        @input="handleAllQtyInput"
                        @keyup.enter="onChangeAllGoodQty"
                      />
                      <h-button type="primary" @click="onChangeAllGoodQty"> 确定 </h-button>
                    </div>
                    <template #reference>
                      <h-plain-button :height="16" :padding-lr="4"> 批量 </h-plain-button>
                    </template>
                  </el-popover>
                </div>
              </template>
              <template #default="{ row, $index }">
                <el-input
                  v-if="!row.isFixed"
                  v-model.trim="row.qty"
                  maxlength="5"
                  @input="handleInputQty($index)"
                />
              </template>
            </el-table-column>

            <!-- 单价 -->
            <!-- <el-table-column prop="unitPrice" label="单价" width="140">
              <template #header>
                <div class="table-header">
                  单价
                  <el-popover
                    ref="changeAllUnitPricePopoverRef"
                    placement="top"
                    trigger="click"
                    :width="220"
                  >
                    <h5 style="margin-bottom: 10px">批量填充单价</h5>
                    <div class="popover-container">
                      <el-input-number
                        v-model.trim="allUnitPrice"
                        placeholder="请输入"
                        :precision="2"
                        :controls="false"
                        :min="0.01"
                        :max="99999.99"
                        @keyup.enter="changeAllUnitPrice"
                      />
                      <h-button type="primary" @click="changeAllUnitPrice"> 确定 </h-button>
                    </div>
                    <template #reference>
                      <h-plain-button :height="16" :padding-lr="4"> 批量 </h-plain-button>
                    </template>
                  </el-popover>
                </div>
              </template>
              <template #default="{ row }">
                <el-input-number
                  v-if="!row.isFixed"
                  v-model.trim="row.price"
                  style="width: 100px"
                  :precision="2"
                  :controls="false"
                  :min="0.01"
                  :max="99999.99"
                >
                  <template #prepend>￥</template>
                </el-input-number>
                <template v-else> {{ '' }} </template>
              </template>
            </el-table-column> -->

            <!-- 金额 -->
            <!-- <el-table-column prop="price" show-overflow-tooltip label="金额" width="160">
              <template #default="{ row }">
                <template v-if="!row.isFixed"> ￥{{ (row.price * row.qty).toFixed(2) }} </template>
                <template v-else> {{ '' }} </template>
              </template>
            </el-table-column> -->

            <!-- 备注 -->
            <el-table-column prop="remark" show-overflow-tooltip label="备注" width="400">
              <template #default="{ row }">
                <el-input
                  v-if="!row.isFixed"
                  v-model.trim="row.remark"
                  type="textarea"
                  clearable
                  placeholder="备注"
                  maxlength="200"
                  show-word-limit
                  resize="both"
                />
              </template>
            </el-table-column>

            <!-- 操作 -->
            <el-table-column fixed="right" width="90" label="操作">
              <template #default="{ row, $index }">
                <h-link v-if="!row.isFixed" type="error" @click="handleDelGood($index)"
                  >删除</h-link
                >
                <h-link v-else @click="onSelectGoodClick">选择产品</h-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 添加产品 -->
    <h-drawer
      v-model="selectGoodDrawerVisible"
      :width="1100"
      unit="px"
      title="添加产品"
      :h-drawer-padding-top="12"
      :loading="getGoodSelectListLoading || getGoodTypeListLoading"
    >
      <div class="product_info">
        <div class="sidebar">
          <div class="title">产品类型</div>
          <div class="content">
            <el-radio-group v-model="goodsType" @change="getGoodSelectList">
              <el-radio :value="1" size="small">成品</el-radio>
              <el-radio :value="2" size="small">物料</el-radio>
            </el-radio-group>
            <ul class="type_list">
              <li
                :class="{
                  type_item: true,
                  active_type_item: getGoodSelectListParam.typeId == null,
                }"
                @click="onGoodTypeClick(null)"
                >全部</li
              >
              <li
                v-for="(item, index) in goodTypeList"
                :key="index"
                :class="{
                  type_item: true,
                  active_type_item: getGoodSelectListParam.typeId == item.id,
                }"
                @click="onGoodTypeClick(item.id)"
              >
                <h-tooltip-text :text="item.name" :height="16" :max-width="240" />
              </li>
            </ul>
            <div class="page_pages">
              <el-pagination
                hide-on-single-page
                :current-page="getGoodTypeListCurrentPage"
                :page-size="getGoodTypeListLimit"
                :total="goodTypeListTotal"
                :pager-count="5"
                size="small"
                layout="total, prev, pager, next"
                @current-change="handleGetGoodTypeListCurrentPageChange"
              />
            </div>
          </div>
        </div>
        <div element-loading-text="加载中..." class="table_container">
          <div class="header">
            <div class="title">产品列表</div>
            <div class="search">
              <el-select
                v-model="getGoodSelectListParam.brandId"
                placeholder="请选择品牌"
                filterable
                clearable
                reserve-keyword
                fit-input-width
                :loading="getGoodBrandOptionsLoading"
                :filter-method="handleGoodBrandListFilter"
                collapse-tags
                :max-collapse-tags="2"
                collapse-tags-tooltip
                @change="getGoodSelectList"
              >
                <el-option
                  v-for="item in goodBrandOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <el-tooltip
                    v-if="item.name.length > 20"
                    :content="item.name"
                    effect="dark"
                    placement="top"
                  >
                    <span>{{ item.name }}</span>
                  </el-tooltip>
                </el-option>
              </el-select>
              <el-input
                v-model.trim="getGoodSelectListParam.keyword"
                clearable
                placeholder="产品型号/产品名称/产品规格"
                @keyup.enter="getGoodSelectList"
                @clear="getGoodSelectList"
              />
              <h-button type="primary" @click="getGoodSelectList">搜索</h-button>
            </div>
          </div>
          <div class="table">
            <el-table
              ref="goodSelectTableInstance"
              :border="true"
              stripe
              resizable
              :data="goodSelectList"
              height="100%"
              @select="handleRemoveGood"
              @selection-change="handleSelectGood"
            >
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
              <!-- 选择框 -->
              <el-table-column show-overflow-tooltip type="selection" width="40" fixed />

              <!-- 编号 -->
              <el-table-column show-overflow-tooltip prop="code" label="编号" />

              <!-- 品牌 -->
              <!-- <el-table-column show-overflow-tooltip prop="brand" label="品牌" /> -->

              <!-- 产品名称 -->
              <el-table-column show-overflow-tooltip prop="name" label="产品名称" />

              <!-- 型号 -->
              <el-table-column show-overflow-tooltip prop="model" label="型号" />

              <!-- 规格 -->
              <el-table-column show-overflow-tooltip prop="specName" label="规格" />

              <!-- 规格图片 -->
              <el-table-column show-overflow-tooltip label="规格图片">
                <template #default="item">
                  <div v-if="item.row.image" class="pic">
                    <h-image
                      :src="item.row.image"
                      fit="contain"
                      :show-del-btn="false"
                      :padding="2"
                      :width="40"
                      :height="25"
                    />
                  </div>
                </template>
              </el-table-column>

              <!-- 质保时间 -->
              <el-table-column show-overflow-tooltip prop="warrantyDay" label="质保时间(天)" />
            </el-table>
          </div>
          <!-- 分页 -->
          <div class="pagination">
            <Pagination
              ref="goodSelectListPaginationInstance"
              :list_total="goodSelectListTotal"
              @size-change="getGoodSelectList"
              @current-change="getGoodSelectList"
            />
          </div>
        </div>
      </div>

      <template #footer>
        <HButton is-modal type="primary" @click="onSelectGoodDrawerConfirm">确定</HButton>
        <HButton is-modal @click="onSelectGoodDrawerCancel">取消</HButton>
      </template>
    </h-drawer>

    <!-- 选择条码弹窗 -->
    <h-drawer
      v-model="selectSnCodeDrawerVisible"
      title="选择条码"
      :width="1200"
      unit="px"
      :loading="getSnCodeListLoading"
      :h-drawer-padding-top="12"
    >
      <div class="select_code">
        <div class="header">
          <div class="info_list">
            <div class="info_item">
              <div class="label">产品名称:</div>
              <h-tooltip-text
                :text="currentAddingSnCodeGood.goodsName || ''"
                :max-width="70"
                :height="16"
                width="auto"
              />
            </div>
            <!-- <div class="info_item">
              <div class="label">产品型号:</div>
              <h-tooltip-text
                :text="currentAddingSnCodeGood.goodsModel || ''"
                :max-width="70"
                :height="16"
                width="auto"
              />
            </div> -->
            <div class="info_item">
              <div class="label">产品规格:</div>
              <h-tooltip-text
                :text="currentAddingSnCodeGood.goodsSpecName || ''"
                :max-width="70"
                :height="16"
                width="auto"
              />
            </div>
            <div class="info_item">
              <div class="label">产品类型:</div>
              <h-tooltip-text
                :text="currentAddingSnCodeGood.goodsType || ''"
                :max-width="70"
                :height="16"
                width="auto"
              />
            </div>
            <div class="info_item">
              <div class="label">产品编号:</div>
              <h-tooltip-text
                :text="currentAddingSnCodeGood.goodsCode || ''"
                :max-width="70"
                :height="16"
                width="auto"
              />
            </div>
          </div>
          <div class="search">
            <h-plain-button @click="onCreateSnCode">创建条码</h-plain-button>
            <el-input
              v-model.trim="getSnCodeListKeyword"
              clearable
              placeholder="条码"
              @keyup.enter="getSnCodeList"
              @clear="getSnCodeList"
            />
            <h-button type="primary" @click="getSnCodeList">搜索</h-button>
          </div>
        </div>
        <div class="table">
          <el-table
            ref="selectCodeTableInstance"
            :border="true"
            :data="snCodeList"
            height="100%"
            resizable
            stripe
            @selection-change="handleSelectSnCode"
          >
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <!-- 选择框 -->
            <el-table-column show-overflow-tooltip type="selection" width="40" fixed />

            <!-- 序号 -->
            <el-table-column label="序号" :align="'center'" width="60" type="index" fixed />

            <!-- 条码 -->
            <el-table-column label="条码" width="150" prop="code" show-overflow-tooltip>
              <template #default="scope">
                <h-link @click="handleToSnCodeDetail(scope.row)">{{ scope.row.code }}</h-link>
              </template>
            </el-table-column>

            <!-- 产品编号 -->
            <el-table-column label="产品编号" prop="goodsCode" show-overflow-tooltip />

            <!-- 品牌 -->
            <!-- <el-table-column label="品牌" prop="goodsBrand" show-overflow-tooltip /> -->

            <!-- 产品名称 -->
            <el-table-column label="产品名称" prop="goodsName" show-overflow-tooltip />

            <!-- 产品型号 -->
            <!-- <el-table-column label="产品型号" prop="goodsModel" show-overflow-tooltip /> -->

            <!-- 产品规格 -->
            <el-table-column label="产品规格" prop="goodsSpecName" show-overflow-tooltip />
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <Pagination
            ref="snCodeListPaginationInstance"
            :list_total="snCodeListTotal"
            @size-change="getSnCodeList"
            @current-change="getSnCodeList(false)"
          />
        </div>
      </div>
      <template #footer>
        <h-button is-modal type="primary" @click="onSelectSnCodeConfirm">确定</h-button>
        <h-button is-modal @click="selectSnCodeDrawerVisible = false">取消</h-button>
      </template>
    </h-drawer>

    <!--审核弹窗-->
    <InWarehouseAudit v-model="auditDialogVisible" :loading="saveLoading" @agree="handleAgree" />

    <!--驳回弹窗-->
    <InWarehouseReject
      v-model="rejectDialogVisible"
      :loading="rejectLoading"
      @reject="handleReject"
    />

    <!-- 创建条码弹窗 -->
    <h-dialog v-model="createSnCodeDialogVisible" title="创建条码" :loading="createSnCodeLoading">
      <el-form
        ref="createSnCodeFormInstance"
        :model="createSnCodeForm"
        :rules="createSnCodeRules"
        label-position="top"
        class="modal_form_content"
        inline-message
      >
        <!-- 批次名称 -->
        <el-form-item label="批次名称" prop="name">
          <el-input v-model.trim="createSnCodeForm.name" placeholder="请输入批次名称" />
        </el-form-item>

        <!-- 条码类型 -->
        <el-form-item label="条码类型">
          <el-radio-group v-model="createSnCodeForm.type" disabled class="ml-4">
            <el-radio :value="1">成品</el-radio>
            <el-radio :value="2">物料</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 产品型号 -->
        <el-form-item label="产品型号">
          <el-input v-model.trim="currentAddingSnCodeGood.goodsModel" disabled placeholder="产品型号" />
        </el-form-item>

        <!-- 产品规格 -->
        <el-form-item label="产品规格">
          <el-input
            v-model.trim="currentAddingSnCodeGood.goodsSpecName"
            disabled
            placeholder="产品规格"
          />
        </el-form-item>

        <!-- 条码数量 -->
        <el-form-item label="条码数量">
          <el-input
            v-model.trim="createSnCodeForm.codeVos[0].qty"
            placeholder="条码数量"
            maxlength="5"
            @input="onChangeCreateSnCodeQty"
          />
        </el-form-item>

        <!-- 质保周期 -->
        <el-form-item label="质保周期">
          <el-input
            v-model.trim="createSnCodeForm.codeVos[0].warrantyDay"
            placeholder="质保周期"
            @input="onChangeCreateSnCodeWarranty"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <h-button is-modal type="primary" @click="onCreateSnCodeConfirm">确认</h-button>
        <h-button is-modal @click="onCreateSnCodeDialogCancel">取消</h-button>
      </template>
    </h-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, nextTick, computed } from 'vue'
  import Pagination from '../../../../components/Pagination/index.vue'
  import { addSave } from '../../../../api/code'
  import { ElSelect, TableInstance, FormInstance, TableColumnCtx } from 'element-plus'
  import _ from 'lodash'
  import { useRoute, useRouter } from 'vue-router'
  import { QuestionFilled } from '@element-plus/icons-vue'
  import { Good, GoodSelect, SnCode, WarehouseOptions, WarehousePositionOptions } from './types'
  import InWarehouseAudit from '@/components/pages/Warehouse/InWarehouse/Audit/InWarehouseAudit.vue'
  import InWarehouseReject from '@/components/pages/Warehouse/InWarehouse/Reject/InWarehouseReject.vue'
  import routeComponentName from '@/config/route-component-name'
  import {
    useWarehouseEntryForm,
    useGetWarehouseEntryDetail,
    useGetWarehouseEntryDetailGoodList,
  } from '@/services/pages/storage/useWarehouseEntry'
  import { brandPageSelect, typePageSelect } from '@/api/goodsInfo'
  import {
    getGoodsStock,
    getInOrOutStoreGoods,
    getStoreCodeList,
    inStoreTypePageSelect,
    storePageSelect,
    storePositionPageSelect,
  } from '@/api/store'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import moment from 'moment'
  import { useTagsViewStore } from '@/store/modules/tagsView'

  const { form, rejectForm, saveLoading, rejectLoading, add, audit, reject, resetForm } =
    useWarehouseEntryForm()
  const { detail, getDetailLoading, getDetail } = useGetWarehouseEntryDetail()
  const {
    goodList: warehouseEntryDetailGoodList,
    getGoodListLoading: getWarehouseEntryDetailGoodListLoading,
    getGoodList: getWarehouseEntryDetailGoodList,
  } = useGetWarehouseEntryDetailGoodList()

  defineOptions({
    name: routeComponentName.storage.inStorageCreate,
  })

  // 入库单号
  const warehouseEntryNo = ref('')

  // 出库仓类型
  const storeType = ref([
    { title: '内部仓库', value: 0 },
    { title: '网点-外部仓库', value: 1 },
    { title: '工程师-外部仓库', value: 2 },
  ])

  // 单据来源
  const source = ref([
    { title: '系统单', value: 1 },
    { title: '工单', value: 2 },
    { title: 'ERP单据', value: 3 },
    { title: '仓库移动端单据', value: 4 },
    { title: '第三方系统单据', value: 5 },
  ])

  // 驳回弹窗显示状态
  const rejectDialogVisible = ref(false)

  // 标签状态管理
  const tagsViewStore = useTagsViewStore()

  // 表单校验规则
  const formRules = ref({
    typeId: [{ required: true, message: '入库类型', trigger: ['blur', 'change'] }],
    storeType: [{ required: true, message: '仓库类型', trigger: ['blur', 'change'] }],
  })

  // 表单组件实例
  const formInstance = ref<FormInstance | null>(null)

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 产品选择抽屉显示状态
  const selectGoodDrawerVisible = ref(false)

  // 产品列表
  const goodList = ref<Array<Good>>([])

  // 获取产品分类列表加载
  const getGoodTypeListLoading = ref(false)

  // 产品分类列表总条数
  const goodTypeListTotal = ref(0)

  // 产品分类列表
  const goodTypeList = ref<Array<GoodTypes>>([])

  // 获取产品品牌下拉选项加载
  const getGoodBrandOptionsLoading = ref(false)

  // 产品品牌下拉选项
  const goodBrandOptions = ref<Array<GoodBrandOption>>([])

  // 产品类型：1-成品，2-物料
  const goodsType = ref<1 | 2>(1)

  // 产品选择列表分页组件实例
  const goodSelectListPaginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 获取产品选择列表加载
  const getGoodSelectListLoading = ref(false)

  // 获取产品选择列表请求参数
  const getGoodSelectListParam = ref({
    brandId: '',
    keyword: '',
    typeId: null,
    typeThreeId: '',
    typeTwoId: '',
  })

  // 产品选择列表总条数
  const goodSelectListTotal = ref(0)

  // 产品选择列表
  const goodSelectList = ref<Array<GoodSelect>>([])

  // 获取产品品牌下拉选项请求关键字
  const getGoodBrandOptionsKeyword = ref('')

  // 产品分类列表当前页码
  const getGoodTypeListCurrentPage = ref(1)

  // 产品分类列表每页显示多少条
  const getGoodTypeListLimit = ref(13)

  // 产品选择列表的表格组件实例
  const goodSelectTableInstance = ref<TableInstance | null>(null)

  // 被选中的产品列表，用于回显数据
  const selectedGoodList = ref<Array<Good>>([])

  // 需要删除的产品
  const deletedGoodList = ref<Array<GoodSelect>>([])

  // 仓库下拉选项
  const warehouseOptions = ref<Array<WarehouseOptions>>([])

  // 获取仓库下拉选项加载
  const getWarehouseOptionsLoading = ref(false)

  // 获取仓库下拉选项请求关键字
  const getWarehouseOptionsKeyword = ref('')

  // 获取仓位下拉选项请求关键字
  const getWarehousePositionOptionsKeyword = ref('')

  // 获取仓位下拉选项加载
  const getWarehousePositionOptionsLoading = ref(false)

  // 仓库批量选择的id
  const allStoreId = ref('')

  // 是否全部选择的仓库都启用了仓位
  const isAllWarehouseEnablePosition = computed(() => {
    let result = true

    goodList.value.forEach((item) => {
      const warehouse = warehouseOptions.value.find(
        (warehouseOption) => warehouseOption.id === item.storeId,
      )
      if (!warehouse) {
        result = false
        return
      }
      if (!warehouse.enableStorePosition) {
        result = false
      }
    })

    return result
  })

  // 用于填充全部产品的仓位
  const allWarehousePositionId = ref('')

  // 获取所有产品的仓位下拉选项的关键字
  const getAllGoodWarehousePositionOptionsKeyword = ref('')

  // 获取所有产品的仓位下拉选项加载
  const getAllGoodWarehousePositionOptionsLoading = ref(false)

  // 所有产品的数量，用于批量填充
  const allQty = ref('0')

  // 所有产品的单价，用于批量填充
  const allUnitPrice = ref(0.01)

  // 选择条码弹窗显示状态
  const selectSnCodeDrawerVisible = ref(false)

  // 当前正在添加条码的产品
  const currentAddingSnCodeGood = ref<Good>({
    type: 1,
    goodsName: '',
    goodsModel: '',
    goodsSpecName: '',
    goodsBrand: '',
    goodsType: '',
    unit: '',
    systemStock: '',
    stockCodeVos: [],
    qty: '',
    unitPrice: 0,
    price: 0,
    remark: '',
    isFixed: false,
    goodId: '',
    goodSpecId: '',
    storeId: '',
    warehousePositionOptions: [],
    storePositionId: '',
    goodsCode: '',
    tempSelectCodes: [],
    snCodeBeforeAudit: [],
  })

  // 条码分页组件实例
  const snCodeListPaginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 获取条码列表搜索关键字
  const getSnCodeListKeyword = ref('')

  // 获取条码列表加载
  const getSnCodeListLoading = ref(false)

  // 条码列表总条数
  const snCodeListTotal = ref(0)

  // 条码列表
  const snCodeList = ref<Array<SnCode>>([])

  // 创建条码弹窗显示状态
  const createSnCodeDialogVisible = ref(false)

  // 创建条码表单
  const createSnCodeForm = ref<CodeAPIRequest.Create>({
    codeVos: [
      {
        goodsId: null,
        goodsSpecId: null,
        qty: '1',
        warrantyDay: 30,
      },
    ],
    name: '',
    qty: null,
    type: 1,
  })

  // 创建条码表单组件实例
  const createSnCodeFormInstance = ref<FormInstance | null>(null)

  // 创建条码表单校验规则
  const createSnCodeRules = ref({
    name: [{ required: true, message: '请输入批次名称', trigger: ['blur', 'change'] }],
  })

  // 创建条码加载
  const createSnCodeLoading = ref(false)

  // 全局路由对象
  const router = useRouter()

  // 激活路由对象
  const route = useRoute()

  // 是否校验产品列表
  const isVerifyGoods = ref(false)

  // 选择条码表格组件实例
  const selectCodeTableInstance = ref<TableInstance | null>(null)

  // 审核弹窗显示状态
  const auditDialogVisible = ref(false)

  // 单据类型下拉选项
  const documentTypeOptions = ref<Array<WarehouseEntryDocumentTypeOptions>>([])

  // 获取单据类型下拉选项加载
  const getDocumentTypeOptionsLoading = ref(false)

  // 获取单据类型下拉选项请求关键字
  const getDocumentTypeOptionsKeyword = ref('')

  /**
   * 获取表格行的类名，主要用于第一行数据固定显示
   * @param {Object} data - 表格行数据
   */
  const getRowClassName = (data: { row: Good; rowIndex: number }) => {
    if (data.rowIndex === 0) {
      return 'fixed-row'
    }
  }

  /**
   * 选择产品点击事件
   */
  const onSelectGoodClick = () => {
    selectGoodDrawerVisible.value = true
    selectedGoodList.value = _.cloneDeep(goodList.value)
    getGoodTypeList()
    getBrandOptions('')
    getGoodSelectList()
  }

  /**
   * 获取产品分类列表
   */
  const getGoodTypeList = async () => {
    getGoodTypeListLoading.value = true
    const data = {
      limit: getGoodTypeListLimit.value,
      name: '',
      page: getGoodTypeListCurrentPage.value,
    }
    const res = await typePageSelect(data)
    goodTypeList.value = res.data.data.rows
    goodTypeListTotal.value = Number(res.data.data.total)
    getGoodTypeListLoading.value = false
  }

  /**
   * 获取品牌下拉选项
   * @param {String} keyword - 关键字
   */
  const getBrandOptions = async (keyword: string) => {
    getGoodBrandOptionsLoading.value = true
    const res = await brandPageSelect({
      limit: 0,
      name: keyword,
      page: 0,
    })
    goodBrandOptions.value = res.data.data.rows
    getGoodBrandOptionsLoading.value = false
  }

  /**
   * 获取产品信息列表
   */
  const getGoodSelectList = () => {
    nextTick(async () => {
      if (!goodSelectListPaginationInstance.value) {
        return
      }

      if (!goodSelectTableInstance.value) {
        return
      }

      getGoodSelectListLoading.value = true
      const res = await getInOrOutStoreGoods(
        {
          ...getGoodSelectListParam.value,
          limit: goodSelectListPaginationInstance.value.size,
          page: goodSelectListPaginationInstance.value.current,
        },
        goodsType.value,
      )
      getGoodSelectListLoading.value = false
      if (res.data.code === 20000) {
        goodSelectList.value = res.data.data.rows
        goodSelectListTotal.value = Number(res.data.data.total)
      } else {
        HMessageBox.error(res.data.message)
      }

      /**
       * 初步怀疑是数据还没有在表格上渲染上来，所以同步的方式回显数据是回显不了的，所才使用的异步
       */
      setTimeout(() => {
        goodSelectList.value.forEach((item) => {
          const good = selectedGoodList.value.find(
            (_good) => _good.goodId === item.id && _good.goodSpecId === item.specId,
          )
          if (good) {
            goodSelectTableInstance.value.toggleRowSelection(item, true)
          }
        })
      }, 0)
    })
  }

  /**
   * 产品品牌筛选
   */
  const handleGoodBrandListFilter = _.debounce((keyword: string) => {
    if (getGoodBrandOptionsKeyword.value !== keyword) {
      getGoodBrandOptionsKeyword.value = keyword
      getBrandOptions(getGoodBrandOptionsKeyword.value)
    }
  }, 600)

  /**
   * 产品分类列表页码更新事件
   * @param {Number} currentPage - 页码
   */
  const handleGetGoodTypeListCurrentPageChange = (currentPage: number) => {
    getGoodTypeListCurrentPage.value = currentPage
    getGoodTypeList()
  }

  /**
   * 产品分类选择事件
   * @param {(String|null)} id - 产品分类id
   */
  const onGoodTypeClick = (id: null | string) => {
    if (!goodSelectListPaginationInstance.value) {
      return
    }

    goodSelectListPaginationInstance.value.setPage()
    getGoodSelectListParam.value = {
      typeId: id,
      keyword: '',
      brandId: '',
      typeTwoId: '',
      typeThreeId: '',
    }
    getGoodSelectList()
  }

  /**
   * 产品选择抽屉取消点击事件
   */
  const onSelectGoodDrawerCancel = () => {
    deletedGoodList.value.length = 0
    selectedGoodList.value.length = 0
    selectGoodDrawerVisible.value = false
  }

  /**
   * 产品选择事件
   * @param {Array<GoodSelect>} _goodList - 产品列表
   */
  const handleSelectGood = (_goodList: Array<GoodSelect>) => {
    _goodList.forEach((_good) => {
      const good = selectedGoodList.value.find(
        (item) => _good.id === item.goodId && _good.specId === item.goodSpecId,
      )
      if (!good) {
        selectedGoodList.value.push({
          type: goodsType.value,
          goodsName: _good.name,
          goodsModel: _good.model,
          goodsSpecName: _good.specName,
          goodsBrand: _good.brand,
          goodsType: _good.type,
          unit: _good.unit,
          systemStock: '',
          stockCodeVos: [],
          qty: '1',
          unitPrice: 0.01,
          price: _good.price,
          remark: '',
          isFixed: false,
          goodId: _good.id,
          goodSpecId: _good.specId,
          storeId: '',
          warehousePositionOptions: [],
          storePositionId: '',
          goodsCode: _good.code,
          tempSelectCodes: [],
          snCodeBeforeAudit: [],
        })
      }
    })
  }

  /**
   * 产品选择列表的移除产品事件
   * @param {Array<GoodSelect>} _goodList - 产品选择列表
   * @param {GoodSelect} good - 产品
   */
  const handleRemoveGood = (_goodList: Array<GoodSelect>, good: GoodSelect) => {
    const _good = _goodList.find((item) => item.id === good.id && item.specId === good.specId)
    if (!_good) {
      const index = selectedGoodList.value.findIndex(
        (item) => item.goodId === good.id && item.goodSpecId === good.specId,
      )
      if (index >= 0) {
        selectedGoodList.value.splice(index, 1)
        deletedGoodList.value.push(good)
      }
    }
  }

  /**
   * 产品选择抽屉确定点击事件
   */
  const onSelectGoodDrawerConfirm = () => {
    _.cloneDeep(selectedGoodList.value).forEach((item) => {
      const good = goodList.value.find(
        (_good) => _good.goodId === item.goodId && _good.goodSpecId === item.goodSpecId,
      )
      if (!good) {
        goodList.value.push(item)
      }
    })
    deletedGoodList.value.forEach((item) => {
      const index = goodList.value.findIndex(
        (_good) => _good.goodId === item.id && _good.goodSpecId === item.specId,
      )
      if (index >= 0) {
        goodList.value.splice(index, 1)
      }
    })
    selectGoodDrawerVisible.value = false
    deletedGoodList.value.length = 0
    selectedGoodList.value.length = 0
  }

  /**
   * 删除产品事件
   * @param {Number} index - 产品索引
   */
  const handleDelGood = (index: number) => {
    const good = goodList.value.splice(index, 1)
    if (good[0]) {
      const _index = selectedGoodList.value.findIndex(
        (item) => item.goodId === good[0].goodId && item.goodSpecId === good[0].goodSpecId,
      )
      if (_index >= 0) {
        selectedGoodList.value.splice(_index, 1)
      }
    }
  }

  /**
   * 单据日期更新事件
   */
  const handleChangeCreateTime = () => {
    form.value.createTime = moment(form.value.createTime).format('YYYY-MM-DD HH:mm:SS')
  }

  /**
   * 预计入库时间更新事件
   */
  const handleChangeEstimateWarehouseEntryTime = () => {
    form.value.estimateTime = moment(form.value.estimateTime).format('YYYY-MM-DD HH:mm:SS')
  }

  /**
   * 获取仓库下拉
   */
  const getWarehouseOptions = async () => {
    getWarehouseOptionsLoading.value = true
    const res = await storePageSelect(
      {
        limit: 0,
        name: getWarehouseOptionsKeyword.value,
        page: 0,
      },
      form.value.storeType,
    )
    getWarehouseOptionsLoading.value = false
    if (res.data.code === 20000) {
      warehouseOptions.value = res.data.data.rows
    } else {
      HMessageBox.error(res.data.message)
    }
  }

  /**
   * 获取仓库下拉选项事件
   * @param {String} keyword - 关键字
   */
  const handleGetWarehouseOptions = _.debounce((keyword: string) => {
    if (getWarehouseOptionsKeyword.value !== keyword) {
      getWarehouseOptionsKeyword.value = keyword
      getWarehouseOptions()
    }
  }, 600)

  /**
   * 仓库选择事件
   * @param {Good} good - 产品
   * @param {number} index - 产品索引
   */
  const handleSelectWarehouse = (good: Good, index: number) => {
    if (getWarehouseEnableStatus(good.storeId)) {
      getWarehousePositionOptions(good.storeId, index)
    } else {
      getGoodStock(good, index)
    }
  }

  /**
   * 获取仓位下拉选项
   * @param {String} storeId - 仓库id
   * @param {Number} index - 产品索引
   * @param {Boolean} isAutoFill - 是否自动填充
   */
  const getWarehousePositionOptions = async (
    storeId: string,
    index: number,
    isAutoFill = true,
  ): Promise<Array<WarehousePositionOptions>> => {
    if (storeId && index >= 0) {
      getWarehousePositionOptionsLoading.value = true
      const res = await storePositionPageSelect(
        {
          limit: 0,
          name: getWarehousePositionOptionsKeyword.value,
          page: 0,
        },
        storeId,
      )
      getWarehousePositionOptionsLoading.value = false
      if (res.data.code === 20000) {
        if (isAutoFill) {
          goodList.value[index].warehousePositionOptions = res.data.data.rows
        } else {
          return res.data.data.rows
        }
      } else {
        HMessageBox.error(res.data.message)
      }
    }
  }

  /**
   * 更改全部产品的仓库
   */
  const onChangeAllStore = async () => {
    goodList.value = goodList.value.map((good) => {
      return {
        ...good,
        storeId: allStoreId.value,
      }
    })
    if (getWarehouseEnableStatus(allStoreId.value)) {
      const res = await storePositionPageSelect(
        {
          limit: 0,
          name: getWarehousePositionOptionsKeyword.value,
          page: 0,
        },
        allStoreId.value,
      )
      if (res.data.code === 20000) {
        goodList.value = goodList.value.map((good) => {
          return {
            ...good,
            warehousePositionOptions: res.data.data.rows,
          }
        })
      } else {
        HMessageBox.error(res.data.message)
      }
    } else {
      goodList.value.forEach((item, index) => {
        getGoodStock(item, index)
      })
    }
  }

  /**
   * 获取仓库的仓位启用状态
   * @param {String} id - 仓库id
   */
  const getWarehouseEnableStatus = (id: string) => {
    const warehouseOption = warehouseOptions.value.find((item) => item.id === id)
    return warehouseOption && warehouseOption.enableStorePosition
  }

  /**
   * 获取仓位下拉选项事件
   * @param {String} keyword - 搜索关键字
   * @param {String} storeId - 仓库id
   * @param {Number} index - 产品索引
   */
  const handleGetWarehousePositionOptions = _.debounce(
    (keyword: string, storeId: string, index: number) => {
      if (getWarehousePositionOptionsKeyword.value !== keyword) {
        getWarehousePositionOptionsKeyword.value = keyword
        getWarehousePositionOptions(storeId, index)
      }
    },
    600,
  )

  /**
   * 更新全部产品的仓位
   */
  const onChangeAllGoodWarehousePosition = () => {
    goodList.value = goodList.value.map((item, index) => {
      getGoodStock(item, index)
      return {
        ...item,
        storePositionId: allWarehousePositionId.value,
      }
    })
  }

  /**
   * 获取所有产品的仓位下拉选项
   * @param {String} keyword - 搜索关键字
   */
  const handleChangeAllWarehousePositionOptions = _.debounce(async (keyword: string) => {
    if (getAllGoodWarehousePositionOptionsKeyword.value !== keyword) {
      getAllGoodWarehousePositionOptionsKeyword.value = keyword
      const res = await storePositionPageSelect(
        { limit: 0, page: 0, name: getAllGoodWarehousePositionOptionsKeyword.value },
        allStoreId.value,
      )
      if (res.data.code === 20000) {
        goodList.value = goodList.value.map((item) => {
          return {
            ...item,
            warehousePositionOptions: res.data.data.rows,
          }
        })
      } else {
        HMessageBox.error(res.data.message)
      }
    }
  }, 600)

  /**
   * 获取产品库存
   * @param {Good} good - 产品对象
   * @param {Number} index - 产品索引
   */
  const getGoodStock = async (good: Good, index: number) => {
    if (!good.goodId || !good.goodSpecId) {
      return
    }
    const res = await getGoodsStock({
      goodsId: good.goodId,
      goodsSpecId: good.goodSpecId,
      storeId: good.storeId,
      storePositionId: good.storePositionId,
      type: good.type,
    })
    goodList.value[index].systemStock = '0'
    if (res.data.code === 20000) {
      if (res.data.data.row.id) {
        goodList.value[index].price = res.data.data.row.price
      }
      goodList.value[index].systemStock = res.data.data.row.systemStock.toString()
    } else {
      HMessageBox.error(res.data.message)
    }
  }

  /**
   * 填充全部产品的数量
   */
  const onChangeAllGoodQty = () => {
    goodList.value = goodList.value.map((item) => {
      return {
        ...item,
        qty: allQty.value,
      }
    })
  }

  /**
   * 修改所有产品的单价
   */
  const changeAllUnitPrice = () => {
    goodList.value = goodList.value.map((item) => {
      return { ...item, unitPrice: allUnitPrice.value }
    })
  }

  /**
   * 选择条码事件
   */
  const onSelectSnCode = (good: Good) => {
    currentAddingSnCodeGood.value = good
    selectSnCodeDrawerVisible.value = true
    getSnCodeList()
  }

  /**
   * 获取入库条码列表
   */
  const getSnCodeList = (val = true) => {
    nextTick(async () => {
      if (!snCodeListPaginationInstance.value) {
        return
      }
      if (val) {
        snCodeListPaginationInstance.value.setPage()
      }
      const data = {
        goodsId: currentAddingSnCodeGood.value.goodId,
        goodsSpecId: currentAddingSnCodeGood.value.goodSpecId,
        keyword: getSnCodeListKeyword.value,
        limit: snCodeListPaginationInstance.value.size,
        page: snCodeListPaginationInstance.value.current,
        storeId: null,
        storePositionId: null,
        type: currentAddingSnCodeGood.value.type,
      }
      getSnCodeListLoading.value = true
      const res = await getStoreCodeList(data)
      if (res.data.code === 20000) {
        snCodeListTotal.value = Number(res.data.data.total)
        snCodeList.value = res.data.data.rows

        // 设置定时器是为了解决数据还没来得及渲染就回显是回显不成功的问题
        setTimeout(() => {
          if (selectCodeTableInstance.value) {
            const goodIndex = goodList.value.findIndex(
              (item) =>
                item.goodId === currentAddingSnCodeGood.value.goodId &&
                item.goodSpecId === currentAddingSnCodeGood.value.goodSpecId,
            )
            snCodeList.value.forEach((snCode) => {
              const code = goodList.value[goodIndex].stockCodeVos.find(
                (item) => item.id === snCode.id,
              )
              if (code) {
                selectCodeTableInstance.value.toggleRowSelection(snCode, true)
              }
            })
          }
        }, 0)
      }
      getSnCodeListLoading.value = false
    })
  }

  /**
   * 创建条码事件
   */
  const onCreateSnCode = () => {
    createSnCodeDialogVisible.value = true
    createSnCodeForm.value = {
      codeVos: [
        {
          goodsId: currentAddingSnCodeGood.value.goodId,
          goodsSpecId: currentAddingSnCodeGood.value.goodSpecId,
          qty: currentAddingSnCodeGood.value.qty,
          warrantyDay: 30,
        },
      ],
      name: '',
      qty: '',
      type: currentAddingSnCodeGood.value.type,
    }
  }

  /**
   * 创建条码数量更新事件
   */
  const onChangeCreateSnCodeQty = () => {
    createSnCodeForm.value.codeVos[0].qty = createSnCodeForm.value.codeVos[0].qty.replace(
      /[^0-9]/g,
      '',
    )
    if (createSnCodeForm.value.codeVos[0].qty <= '0') {
      createSnCodeForm.value.codeVos[0].qty = '1'
    }
  }

  /**
   * 创建条码质保天数更新事件
   */
  const onChangeCreateSnCodeWarranty = () => {
    const __warrantyDay = createSnCodeForm.value.codeVos[0].warrantyDay.toString()
    createSnCodeForm.value.codeVos[0].warrantyDay = Number(__warrantyDay.replace(/[^0-9]/g, ''))
    if (createSnCodeForm.value.codeVos[0].warrantyDay <= 0) {
      createSnCodeForm.value.codeVos[0].warrantyDay = 30
    }
  }

  /**
   * 创建条码取消事件
   */
  const onCreateSnCodeDialogCancel = () => {
    createSnCodeForm.value = {
      codeVos: [
        {
          goodsId: null,
          goodsSpecId: null,
          qty: '1',
          warrantyDay: 30,
        },
      ],
      name: '',
      qty: null,
      type: 1,
    }
    createSnCodeDialogVisible.value = false
  }

  /**
   * 创建条码弹窗确定事件
   */
  const onCreateSnCodeConfirm = async () => {
    if (!createSnCodeFormInstance.value) {
      return
    }

    try {
      await createSnCodeFormInstance.value.validate()
      createSnCodeForm.value.qty = createSnCodeForm.value.codeVos[0].qty
      createSnCodeLoading.value = true
      const res = await addSave(createSnCodeForm.value)
      createSnCodeLoading.value = false
      if (res.data.code === 20000) {
        HMessage.success('创建条码成功')
        onCreateSnCodeDialogCancel()
        getSnCodeList()
      } else {
        HMessageBox.error(res.data.message)
      }
    } catch (error) {
      // error
    }
  }

  /**
   * 条码点击事件
   * @param {SnCode} snCode - 条码对象
   */
  const handleToSnCodeDetail = (snCode: SnCode) => {
    selectSnCodeDrawerVisible.value = false
    router.push({ path: `/code/codetail/${snCode.id}/${snCode.tableType}` })
  }

  /**
   * 条码选择事件
   */
  const handleSelectSnCode = (codeList: Array<SnCode>) => {
    const goodIndex = goodList.value.findIndex(
      (item) =>
        item.goodId === currentAddingSnCodeGood.value.goodId &&
        item.goodSpecId === currentAddingSnCodeGood.value.goodSpecId,
    )
    if (goodIndex >= 0) {
      goodList.value[goodIndex].tempSelectCodes = codeList.map((item) => {
        return {
          id: item.id,
          code: item.code,
        }
      })
    }
  }

  /**
   * 条码选择确定事件
   */
  const onSelectSnCodeConfirm = () => {
    const index = goodList.value.findIndex(
      (item) =>
        item.goodId === currentAddingSnCodeGood.value.goodId &&
        item.goodSpecId === currentAddingSnCodeGood.value.goodSpecId,
    )
    if (Number(goodList.value[index].qty) < goodList.value[index].tempSelectCodes.length) {
      HMessageBox.error('录入的条码数量不能超过出库条码总数')
      return
    }
    goodList.value[index].stockCodeVos = _.cloneDeep(
      goodList.value[index].tempSelectCodes.map((item) => {
        return {
          code: item.code,
          id: item.id,
        }
      }),
    )
    if (goodList.value[index].stockCodeVos.length === 0) {
      goodList.value[index].stockCodeVos = _.cloneDeep(goodList.value[index].snCodeBeforeAudit)
    }
    goodList.value[index].tempSelectCodes.length = 0
    selectSnCodeDrawerVisible.value = false
  }

  /**
   * 表单校验
   */
  const formValidate = async () => {
    if (formInstance.value && tableInstance.value) {
      try {
        isVerifyGoods.value = true
        await formInstance.value.validate()
        if (goodList.value.length <= 1) {
          HMessageBox.error('请选择产品')
          throw new Error('请选择产品')
        }
        for (let i = 1; i < goodList.value.length; i++) {
          const good = goodList.value[i]
          if (!good.storeId) {
            HMessageBox.error('请选择仓库')
            throw new Error('请选择仓库')
          }

          if (getWarehouseEnableStatus(good.storeId) && !good.storePositionId) {
            HMessageBox.error('请选择仓位')
            throw new Error('请选择仓位')
          }

          if (good.stockCodeVos.length === 0) {
            HMessageBox.error('请选择条码')
            throw new Error('请选择条码')
          }
        }

        return
      } catch (error) {
        throw new Error('表单校验不通过')
      }
    }
  }

  /**
   * 获取入库物料
   */
  const getMaterialVos = () => {
    return goodList.value
      .filter((item) => !item.isFixed)
      .map((item) => {
        return {
          goodsId: item.goodId,
          goodsSpecId: item.goodSpecId,
          id: '',
          price: item.price,
          qty: item.qty,
          stockCodeVos: item.stockCodeVos.map((item) => {
            return {
              code: item.code,
            }
          }),
          storeId: item.storeId,
          storePositionId: item.storePositionId,
          type: item.type,
          remark: item.remark,
        }
      })
  }

  /**
   * 保存事件
   */
  const onSave = async () => {
    try {
      await formValidate()
      form.value.inboundMaterialVos = getMaterialVos()
      const res = await add()
      if (res.code === 20000) {
        HMessage.success('保存成功')
        onCancel()
      } else {
        HMessageBox.error(res.message)
      }
    } catch (error) {
      // error
    }
  }

  /**
   * 审核弹窗的通过事件
   * @param {String} remark - 通过备注
   */
  const handleAgree = async (remark: string) => {
    form.value.reviewRemark = remark
    const res = await audit()
    if (res.code === 20000) {
      HMessage.success('审核成功')
      onCancel()
      return
    }
    HMessageBox.error(res.message)
  }

  /**
   * 审核事件
   */
  const onCheck = async () => {
    try {
      await formValidate()
      form.value.inboundMaterialVos = getMaterialVos()
      auditDialogVisible.value = true
    } catch (error) {
      // error
    }
  }

  /**
   * 取消事件
   */
  const onCancel = () => {
    tagsViewStore.delView(route.path)
    router.push('/storage/intb')
    resetForm()
  }

  /**
   * 驳回弹窗的驳回事件
   */
  const handleReject = async (remark: string) => {
    rejectForm.value.remark = remark
    const res = await reject(route.params.id as string)
    if (res.code === 20000) {
      HMessage.success('驳回成功')
      onCancel()
      return
    }

    HMessageBox.error(res.message)
  }

  /**
   * 表格合计
   */
  const getSummary = (param: { columns: TableColumnCtx<any>[]; data: Array<Good> }) => {
    const { columns, data } = param
    const sums: string[] = []
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[0] = '合计'
        return
      }

      if (column.property === 'qty') {
        let total = 0
        data.forEach((good) => {
          if (!good.isFixed) {
            total += Number(good.qty)
          }
        })
        sums[index] = String(total)
      }

      if (column.property === 'unitPrice') {
        let total = 0
        data.forEach((good) => {
          if (!good.isFixed) {
            total += good.price * 100
          }
        })
        sums[index] = (total / 100).toFixed(2)
      }

      if (column.property === 'price') {
        let total = 0
        data.forEach((good) => {
          if (!good.isFixed) {
            total += Number(good.qty) * good.price
          }
        })
        sums[index] = total.toFixed(2)
      }
    })

    return sums
  }

  /**
   * 数量输入事件
   * @param {Number} index - 产品索引
   */
  const handleInputQty = (index: number) => {
    goodList.value[index].qty = goodList.value[index].qty.replace(/[^\d]/g, '')
    if (Number(goodList.value[index].qty) <= 0) {
      goodList.value[index].qty = '1'
    }

    if (Number(goodList.value[index].qty) > 99999) {
      goodList.value[index].qty = '99999'
    }
  }

  /**
   * 批量数量输入事件
   */
  const handleAllQtyInput = () => {
    allQty.value = allQty.value.replace(/[^\d]/g, '')
    if (Number(allQty.value) <= 0) {
      allQty.value = '1'
    }

    if (Number(allQty.value) > 99999) {
      allQty.value = '99999'
    }
  }

  /**
   * 获取单据类型
   */
  const getDocumentTypeOptions = async () => {
    getDocumentTypeOptionsLoading.value = true
    const res = await inStoreTypePageSelect({
      limit: 0,
      name: getDocumentTypeOptionsKeyword.value,
      page: 0,
    })
    if (res) {
      if (res.data.code == 20000) {
        documentTypeOptions.value = res.data.data.rows
      } else {
        HMessageBox.error(res.data.message)
      }
    }
    getDocumentTypeOptionsLoading.value = false
  }

  /**
   * 获取单据类型下拉选项搜索事件
   * @param {String} keyword - 搜索关键字
   */
  const handleGetDocumentTypeOptions = _.debounce((keyword: string) => {
    if (keyword !== getDocumentTypeOptionsKeyword.value) {
      getAllGoodWarehousePositionOptionsKeyword.value = keyword
      getDocumentTypeOptions()
    }
  }, 600)

  /**
   * 单据类型选择事件
   */
  const onDocumentTypeChange = () => {
    warehouseOptions.value = []
    goodList.value = goodList.value.map((good) => {
      good.storeId = ''
      good.storePositionId = ''
      good.warehousePositionOptions = []
      good.systemStock = null
      good.stockCodeVos = []
      good.tempSelectCodes = []
      return good
    })
    getWarehouseOptions()
  }

  onMounted(async () => {
    goodList.value = [
      {
        type: 1,
        goodsName: '',
        goodsModel: '',
        goodsSpecName: '',
        goodsBrand: '',
        goodsType: '',
        unit: '',
        systemStock: '',
        stockCodeVos: [],
        qty: '',
        unitPrice: 0,
        price: 0,
        remark: '',
        isFixed: true,
        goodId: '',
        goodSpecId: '',
        storeId: '',
        warehousePositionOptions: [],
        storePositionId: '',
        goodsCode: '',
        tempSelectCodes: [],
        snCodeBeforeAudit: [],
      },
    ]
    getWarehouseOptions()
    getDocumentTypeOptions()
    if (route.params.id) {
      await getDetail(route.params.id as string)
      form.value = {
        createTime: detail.value.createTime,
        estimateTime: detail.value.estimateTime,
        id: detail.value.id,
        delInboundMaterialIds: [],
        inboundMaterialVos: [],
        remark: detail.value.remark,
        reviewRemark: detail.value.reviewRemark,
        source: detail.value.source,
        storeType: detail.value.storeType,
        typeId: detail.value.typeId,
      }
      warehouseEntryNo.value = detail.value.inboundNo
      await getWarehouseEntryDetailGoodList(route.params.id as string)
      warehouseEntryDetailGoodList.value.forEach(async (item, index) => {
        const warehousePositionOptions = await getWarehousePositionOptions(
          item.storeId,
          index,
          false,
        )
        goodList.value.push({
          type: item.type,
          goodsName: item.goodsName,
          goodsModel: item.goodsModel,
          goodsSpecName: item.goodsSpecName,
          goodsBrand: item.goodsBrand,
          goodsType: item.goodsType,
          goodsCode: '',
          unit: item.goodsUnit,
          systemStock: String(item.systemStock),
          stockCodeVos: item.stockCodeVos.map((code) => {
            return {
              id: code.codeId,
              code: code.code,
            }
          }),
          qty: String(item.qty),
          unitPrice: item.price,
          price: item.price,
          remark: item.remark,
          isFixed: false,
          goodId: item.goodsId,
          goodSpecId: item.goodsSpecId,
          storeId: item.storeId,
          warehousePositionOptions,
          storePositionId: item.storePositionId,
          tempSelectCodes: item.stockCodeVos.map((code) => {
            return {
              id: code.codeId,
              code: code.code,
            }
          }),
          snCodeBeforeAudit: item.stockCodeVos.map((code) => {
            return {
              id: code.codeId,
              code: code.code,
            }
          }),
        })
      })
    }
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
